<template>
    <div>
        <Row style="margin:5px 0px 3px 5px" >
            <i-col span="1" >
                <Button  size="default"  type="primary" @click="btn_refresh">刷新</Button>
            </i-col>
            <i-col  span="2" offset="1" >
                <Button  size="default"  type="primary" @click="btn_stop_timer" >停止刷新</Button>
            </i-col>
            <i-col  span="2" offset="1" >
                <Button  size="default"  type="primary" @click="btn_get_problem_deployments">故障部署</Button>
            </i-col>
            <i-col span="1" offset="1">
                <Dropdown>
                    <a href="javascript:void(0)">
                        <Icon type="ios-create-outline" size="40" />
                    </a>
                    <DropdownMenu slot="list" placement="bottom-end">
                        <DropdownMenu><a class="button-link"  @click="btn_update_replicas" >扩缩容</a></DropdownMenu>
                        <DropdownMenu><a class="button-link"  @click="btn_add_toleration" >添加容忍</a></DropdownMenu>
                        <DropdownMenu><a class="button-link"  @click="btn_add_node_affinity" >添加节点亲和性</a></DropdownMenu>
                        <DropdownMenu><a class="button-link"  @click="btn_add_pod_anti_affinity" >添加Pod互斥调度</a></DropdownMenu>
                    </DropdownMenu>
                </Dropdown>
            </i-col>
            <i-col  span="1"  >
                <Dropdown>
                    <a href="javascript:void(0)">
                        <Icon type="ios-trash" size="40" />
                    </a>
                    <DropdownMenu slot="list" placement="bottom-end">
                        <DropdownMenu><a class="button-link"   @click="btn_del_deploy" >删除Deploy</a></DropdownMenu>
                        <DropdownMenu><a class="button-link"   @click="btn_del_toleration" >删除容忍</a></DropdownMenu>
                        <DropdownMenu><a class="button-link"   @click="btn_del_node_affinity" >删除节点亲和性</a></DropdownMenu>
                        <DropdownMenu><a class="button-link"   @click="btn_del_pod_anti_affinity" >删除Pod互斥调度</a></DropdownMenu>
                        
                    </DropdownMenu>
                </Dropdown>
            </i-col>
        </Row>
        <i-table size="default"   border stripe  ref="deployment_table" @on-selection-change="onSelect"  :columns="format" :data="show_list" :height="sharedState.tableHeight" >
            <template slot-scope="{ row, index }" slot="action">
                <Button  size="default"   type="primary"  @click="btn_edit_deploy(index)"> 编辑</Button>
            </template>
        </i-table >
        <div style="text-align: center;margin-top: 10px;">
            <Page ref="page" :total="total" :page-size="pageSize"  @on-change="changePage" show-total/>
        </div>

        <!-- 添加容忍模态框  -->
        <AddTolerlationModal :isShow="show_add_toleration_modal" :deploy_name="deploy_name" @closeModal="closeAddTolerationModal"  @addSuccess="onAddTolerationSuccess" ></AddTolerlationModal>

        <!-- 删除容忍模态框 -->
        <DeleteTolerlationModal :isShow="show_del_toleration_modal" :deploy_name="deploy_name" :tolerations="tolerations"  @closeModal="closeDeleteTolerationModal"  @deleteSuccess="onDeleteTolerationSuccess" ></DeleteTolerlationModal>

        <!-- 添加节点亲和性模态框 -->
        <AddNodeAffinityModal  :isShow="show_add_node_affinity_modal" :deploy_name="deploy_name" @closeModal="closeAddNodeAffinityModal"  @addSuccess="onAddNodeAffinitySuccess" ></AddNodeAffinityModal>

        <!-- 添加POD互斥模态框 -->
        <AddPodAntiAffinityModal :isShow="show_add_pod_anti_affinity_modal" :deploy_name="deploy_name" @closeModal="closeAddPodAntiAffinityModal"  @addSuccess="onAddPodAntiAffinitySuccess"> </AddPodAntiAffinityModal>

        <!-- 编辑模态框 -->
        <Modal v-model="show_edit_deploy_modal" width="60vw" class="vertical-center-modal" >
            编辑资源
            <div>
                <yaml-editor  v-model="value"   />
            </div>
            <div style="margin: 5px 0 0 0 ">
                <Row>
                    <i-col span="4"><Button  size="default"  type="primary"    @click="submit_update_deployment">更新</Button></i-col>
                    <i-col span="3"><Button  size="default"  type="primary"     @click="cacel_update_deploy">取消</Button></i-col>
                </Row>
            </div>
            <div slot="footer">
            </div> 

        </Modal>
    </div>
</template>

<script>
import axios from 'axios';
import {k8s_namespace_post} from '@/api/http'
import {  
    get_deployment_list,
    update_replicas,delete_deploy, 
    get_deployment_object,
    get_problem_deployments,
    update_deployment_object,
    delete_node_affinity,
    delete_pod_anti_affinity
} from  '@/api'
import { delete_namespace_resource,get_placement,show_simple_page } from '@/common/util.js'
import YAML from 'json2yaml';
import YamlEditor  from '@/lib/editor/yamlEditor';
import store from '@/store'
import AddTolerlationModal from './lib/toleration/add'
import DeleteTolerlationModal from './lib/toleration/delete'
import AddNodeAffinityModal from './lib/nodeAffinity/add'
import AddPodAntiAffinityModal from './lib/podAntiAffinity/add'
export default {
    components: { YamlEditor, AddTolerlationModal, DeleteTolerlationModal, AddNodeAffinityModal, AddPodAntiAffinityModal},
    data() {
        return {
            sharedState: store.state,
            format: [
                {
                    type: 'selection',width: 60, align: 'center',fixed:"left", 
                },
                {
                    title: '名字',key: 'name',align: 'center',width:175,fixed:"left",
                    render: (h,params) => {
                        return h('a',{
                                style: {
                                    color: 'blue'
                                },
                                on: {
                                    click: ()=>{                       
                                        this.handleLink(params);
                                    }
                                }
                            },params.row.name)
                        
                    }
                },
                {
                    title: '命名空间',key: 'namespace',align: 'center',width:150,
                },
                {
                    title: 'pods',key: 'pods',align: 'center',width:80,
                },
                {
                    title: '标签',key: 'labels',align: 'center',width:100,
                    render: (h, params) => {
                        let labels = params.row.labels
                        let val = ''
                        for(let key in labels){
                            val = val+ key+":"+labels[key]+"\n"
                        }
                        if(labels == null){
                            return h('p','无')
                        }else{

                            // let len = val.split('\n').length -1
                            // if(len > 0 && len < 3){
                            //     return h('pre',val)
                            // }else{
                                let placement = get_placement(params)
                                return h('Poptip', {props:{'trigger':'hover','word-wrap':true,'placement':placement,content:val}},[
                                        h('a', '显示')
                                ]);
                            // }
                        }
                    }
                },
                {
                    title: '容忍',key: 'tolerations',align: 'center',width:80,
                   render : (h,params) => {
                        let tolerations = params.row.tolerations 
                        if (tolerations == null ){
                            return   h('p','无')
                        }else{
                            let value = JSON.stringify(tolerations,undefined,4)
                            let placement = get_placement(params)
                            return h('Poptip', {props:{'trigger':'hover','word-wrap':true,'placement':placement,content:value}},[
                                    h('a', '显示')
                            ]);
                        }
                    }
                },
                {
                    title: '节点选择',key: 'node_selector',align: 'center',width:80,
                   render : (h,params) => {
                        let node_selector = params.row.node_selector 
                        if (node_selector == null ){
                            return   h('p','无')
                        }else{
                            let value = JSON.stringify(node_selector,undefined,4)
                            let placement = get_placement(params)
                            return h('Poptip', {props:{'trigger':'hover','word-wrap':true,'placement':placement,content:value}},[
                                    h('a', '显示')
                            ]);
                        }
                    }
                },

                {
                    title: '节点亲和',key: 'affinify',align: 'center',width:80,
                    render : (h,params) => {
                        let affinity  = params.row.affinity
                        if(affinity == null){
                            return h('p','无')
                        }
                        let node_affinity = affinity['nodeAffinity']
                        if (node_affinity == null ){
                            return   h('p','无')
                        }else{
                            let value = JSON.stringify(node_affinity,undefined,4)
                            let placement = get_placement(params)
                            return h('Poptip', {props:{'trigger':'hover','word-wrap':true,'placement':placement,content:value}},[
                                    h('a', '显示')
                            ]);
                        }
                    }
                },
                {
                    title: 'Pod亲和',key: 'affinify',align: 'center',width:80,
                    render : (h,params) => {
                        let affinity  = params.row.affinity
                        if(affinity == null){
                            return h('p','无')
                        }
                        let pod_affinity = affinity['podAffinity']
                        if (pod_affinity == null ){
                            return   h('p','无')
                        }else{
                            let value = JSON.stringify(pod_affinity,undefined,4)
                            let placement = get_placement(params)
                            return h('Poptip', {props:{'trigger':'hover','word-wrap':true,'placement':placement,content:value}},[
                                    h('a', '显示')
                            ]);
                        }
                    }
                },
                {
                    title: 'Pod互斥',key: 'affinify',align: 'center',width:80,
                    render : (h,params) => {
                        let affinity  = params.row.affinity
                        if(affinity == null){
                            return h('p','无')
                        }
                        let pod_anti_affinity = affinity['podAntiAffinity']
                        if (pod_anti_affinity == null ){
                            return   h('p','无')
                        }else{
                            let value = JSON.stringify(pod_anti_affinity,undefined,4)
                            let placement = get_placement(params)
                            return h('Poptip', {props:{'trigger':'hover','word-wrap':true,'placement':placement,content:value}},[
                                    h('a', '显示')
                            ]);
                        }
                    }
                },
                {
                    title: '更新策略',key: 'strategy',align: 'center',width:80,
                    render : (h,params) => {
                        let strategy  = params.row.strategy
                        if(strategy == null){
                            return h('p','无')
                        } else{
                            let value = JSON.stringify(strategy,undefined,4)
                            let placement = get_placement(params)
                            return h('Poptip', {props:{'trigger':'hover','word-wrap':true,'placement':placement,content:value}},[
                                    h('a', '显示')
                            ]);
                        }
                    }
                },
                {
                    title: '镜像',key: 'image',align: 'center',width:200,
                    render : (h,params) => {
                        let image  = params.row.image
                        if(image == null){
                            return h('p','无')
                        } else{
                            let temp = image.split('/')
                            let value = temp[temp.length -1 ]
                            return h('p',value)
                        }
                    }
                },
                {
                    title: '创建时间',key: 'create_time',align: 'center',width:200,
                },
                {
                    title: '',slot: 'action',width: 100,align: 'center',fixed: 'right'
                }
            ],
            total_list: [],
            show_list: [],
            // 分页
            total: 0,
            pageSize: 10,

            // 多选
            selecteds: [],
            // 添加容忍模态框
            show_add_toleration_modal: false,
            show_del_toleration_modal: false,
            show_add_node_affinity_modal: false,
            show_del_node_affinity_modal: false,
            show_add_pod_anti_affinity_modal: false,
            show_del_pod_anti_affinity_modal: false,
            show_edit_deploy_modal: false,

            // 删除容忍
            tolerations: null,
            
            deploy_name: '',
            value: '',
            is_problem: 0,
        }
    },
    methods: {
        btn_refresh(){
            this.refresh()
        },
        to_yaml(obj) {
            try {
                let yaml = YAML.stringify(obj)
                return yaml
            } catch (e) {
                alert(e)
            }
        },
        closeDeleteTolerationModal() {
            this.show_del_toleration_modal = false
        },
        onDeleteTolerationSuccess() {
            this.refresh()
        },
        closeAddTolerationModal(){
            this.show_add_toleration_modal = false
        },
        onAddTolerationSuccess(){
            this.refresh()
        },
        closeAddNodeAffinityModal(){
            this.show_add_node_affinity_modal = false
        },
        onAddNodeAffinitySuccess(){
            this.refresh()
        },
        closeAddPodAntiAffinityModal(){
            this.show_add_pod_anti_affinity_modal = false
        },
        onAddPodAntiAffinitySuccess(){
            this.refresh()
        },
        submit_update_deployment(){
            let name = this.deploy_name
            let data = {
                "name": name,
                "content": this.value,
            }
            k8s_namespace_post(update_deployment_object,data).then(response=>{
                let info = JSON.stringify(response.data)
                if(info.indexOf('ok') != -1) {
                    this.$Message.success('更新资源成功')
                    this.show_edit_deploy_modal = false
                    this.refresh()
                }else {
                    alert(info)
                }
            })
        },
        btn_get_problem_deployments(){
            this.is_problem = 1
            this.refresh()
        },
        btn_edit_deploy(index){
            let namespace = localStorage.getItem('currentNameSpace')
            if (namespace == "all"){
                alert("此操作需要切换到具体的命名空间")
                return
            }
            let name = this.show_list[index].name
            this.deploy_name = name
            let data = {
                "name": name,
            }
            // k8s_namespace_post(get_deployment_object,data).then(response=>{
            //     let res = response.data
            //     let obj = res['obj']
            //     this.value = this.to_yaml(obj)
                
            //     this.show_edit_deploy_modal = true
            // })
            let headers = {}
            let cluster = localStorage.getItem('currentCluster')
            headers["cluster_name"] =  cluster 
            data["namespace"] = namespace
            axios({
                method:'post',
                url:get_deployment_object,
                data:JSON.stringify(data),
                headers:headers,
                timeout: 2000,
                responseType: 'blob',
            }).then(res =>{
                if (typeof FileReader === "undefined") { 
                    this.$Message.error("您的浏览器不支持读取文件")
                    return;
                }
                let _that = this;
                let reader = new FileReader();
                reader.readAsText(res.data);
                reader.onloadend = function (e) { 
                    _that.value=e.target.result;
                    console.log(e.target.result)
                    _that.show_edit_deploy_modal = true;
                }
            }).catch(error => {
                console.log(error)
                this.$Message.error("请求异常,查看console")
            })
        },
        cacel_update_deploy(){
            this.show_edit_deploy_modal=false
        },

        // 删除POD互斥
        delete_pod_anti_affinity(deploy_name){
            let data={"name":deploy_name}
            k8s_namespace_post(delete_pod_anti_affinity,data).then( (response) => {
                let info = JSON.stringify(response.data)
                if(info.indexOf('ok') != -1) {
                    this.$Message.success('删除POD互斥调度成功')
                    this.refresh()
                }else {
                    alert(info)
                }
            })
        },
        // 删除POD互斥调度点击事件
        btn_del_pod_anti_affinity(){
            if(!this.check()) return
            let select_count = this.selecteds.length
            if (select_count > 1){
                this.$Message.error("此操作暂时不能批量")
                return false
            }

            let  name = this.selecteds[0].name
            if(this.selecteds[0].affinity == null){
                this.$Message.error("没有亲和性设置")
                return
            }
            let pod_anti_affinity = this.selecteds[0].affinity.podAntiAffinity
            if(pod_anti_affinity==null || pod_anti_affinity=='' ) {
                this.$Message.error("没有设置互斥调度")
                return
            }
            
            this.deploy_name = name
            let result = confirm("确定要删除"+name+"POD互斥调度吗(一次性清空，不管设置了几项)?")
            if(result == false) return false
            this.delete_pod_anti_affinity(name)
        },
        // 点击添加pod反亲和性事件
        btn_add_pod_anti_affinity(){
            if(!this.check()) return
            let select_count = this.selecteds.length
            if (select_count > 1){
                this.$Message.error("此操作暂时不能批量")
                return false
            }
            let  name = this.selecteds[0].name
            
            this.deploy_name = name
            // 显示模态框
            this.show_add_pod_anti_affinity_modal = true
        },
        // 删除节点亲和性
        delete_node_affinity(deploy_name) {
            let data = { "name": deploy_name }
            k8s_namespace_post(delete_node_affinity, data).then((response) => {
                let info = JSON.stringify(response.data)
                if (info.indexOf('ok') != -1) {
                    this.$Message.success('删除节点亲和成功')
                    this.refresh()
                } else {
                    alert(info)
                }
            })
        },
        // 点击删除节点亲和性事件
        btn_del_node_affinity(){
            if(!this.check()) return
            let select_count = this.selecteds.length
            if (select_count > 1){
                this.$Message.error("此操作暂时不能批量")
                return false
            }
            let  name = this.selecteds[0].name
            if(this.selecteds[0].affinity == null){
                this.$Message.error("没有亲和性设置")
                return
            }
            let node_affinity = this.selecteds[0].affinity.nodeAffinity
            if(node_affinity==null || node_affinity=='' ) {
                this.$Message.error("没有设置节点亲和性")
                return
            }
            
            this.deploy_name = name
            let result = confirm("确定要删除"+name+"节点亲和性吗(一次性清空,不管有多少项)?")
            if(result == false) return false
            this.delete_node_affinity(name)
        },
        // 添加添加节点亲和性事件
        btn_add_node_affinity(){
            if(!this.check()) return
            let select_count = this.selecteds.length
            if (select_count > 1){
                this.$Message.error("此操作暂时不能批量")
                return false
            }
            let  name = this.selecteds[0].name
            this.deploy_name = name
            this.show_add_node_affinity_modal = true
        } ,
        // 删除容忍点击事件
        btn_del_toleration(){
            console.log('btn_del_toleration')
            if(!this.check()) return
            let select_count = this.selecteds.length
            if (select_count > 1){
                this.$Message.error("此操作暂时不能批量")
                return false
            }
            let  name = this.selecteds[0].name
            let tolerations = this.selecteds[0].tolerations
            this.tolerations = tolerations
            console.log("即将删除容忍:",this.tolerations)
            if(tolerations==null || tolerations=='' ) {
                this.$Message.error("没有设置容忍")
                return
            }
            this.deploy_name = name
            this.show_del_toleration_modal = true
        },
        // 点击添加容忍事件
        btn_add_toleration(){
            console.log("btn_add_toleration")
            if(!this.check()) return
            let select_count = this.selecteds.length
            if (select_count > 1){
                this.$Message.error("此操作暂时不能批量")
                return false
            }
            let  name = this.selecteds[0].name
            this.deploy_name = name
            this.show_add_toleration_modal = true
        },
        // 点击扩缩容
        btn_update_replicas(){
            if(!this.check()) return
            let result = prompt("输入1-10副本数")
            if(result == null) return
        
            if(result=="" || ! /^[0-9]+$/.test(result)){
                alert("您输入数据为空或者含字母,请输入1-10内整数")
                return
            }
            let replicas=parseInt(result)
            // console.log(replicas)
            if(replicas < 1 || replicas >10 ){
                alert("副本数不在1-10之间")
                return
            }
            for(let i=0;i<this.selecteds.length;i++){
                let name = this.selecteds[i].name
                this.update_replicas(name,replicas)
            }
        },
        // 提交扩缩容ajax请求
        update_replicas(deploy_name,replicas){
            let data = {"name":deploy_name,'replicas':replicas}
            k8s_namespace_post(update_replicas,data).then( (response)=>{
                let info = JSON.stringify(response.data)
                if(info.indexOf('ok') != -1) {
                    this.$Message.success('更新'+deploy_name+'副本数到'+replicas+'成功')
                    this.refresh()
                }else {
                    console.log('更新失败')
                    alert(info)
                }
            })
        },
        // 删除deployment点击事件
        btn_del_deploy(){
            if(!this.check()) return
            let result = confirm("确定要删除吗?")
            if(result == false) return false
            for(let i=0;i<this.selecteds.length;i++){
                let name = this.selecteds[i].name
                let namespace = this.selecteds[i].namespace
                delete_namespace_resource(namespace,name,delete_deploy)
                this.refresh()
            }
        },

        // 多选框选项改变就会触发
        onSelect(selection){
            this.selecteds = selection;
            console.log(this.selecteds)
        },
        // 检查有没有选项选中
        check(){
            if(this.selecteds.length == 0 ){
                this.$Message.error("请选择一项")
                return false
            }  
            return true
        },
        // 链接点击事件，进入详情页
        handleLink(params){
            let namespace = params.row.namespace

            const { href } = this.$router.resolve({
                name: 'deploymentDetail'
            });
            window.open(href+"?name="+params.row.name+"&namespace="+namespace, '_blank');
        },
        changePage(index) {
            let _start = (index -1) * this.pageSize
            let _end = index * this.pageSize
            this.show_list = this.total_list.slice(_start,_end)
        },
        refresh() {
            this.selecteds = []
            let url = null
            if(this.is_problem){
                url = get_problem_deployments
            }else{
                url = get_deployment_list
            }
            k8s_namespace_post(url).then( (response) => {
                show_simple_page(this,response)
            })
        },
        btn_stop_timer(){
            clearInterval(this.timer);
        },
    },
    mounted() {
        this.refresh()
        this.timer = setInterval(this.refresh, 20000);
    },
    beforeDestroy() {
        clearInterval(this.timer);
    }
}

</script>
<style lang="less">
    pre{
        white-space: pre-wrap!important;
        word-wrap: break-word!important;
        *white-space:normal!important;
    }
    .button-link {
        font-size:18px;
        color: black;
        padding:25px;
        line-height:60px;
    }
    // .ivu-modal-content{
    //      height: 95vh;
    //      overflow-y: auto;
    // }
    .vertical-center-modal{
        display: flex;
        align-items: center;
        justify-content: center;
        .ivu-modal{
            top: 0;
        }
    }
</style>
